<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<meta charset="utf-8">

<head >
<th:block th:include="include :: header('修改文章')"/>
<th:block th:include="include::bootstrap-select-css" />
<th:block th:include="include :: oly_froala_css" />
<th:block th:include="include :: oly_tagsinput_css" />
<th:block th:include="include :: bootstrap-fileinput-css" />

<style>
	.keyinput>.bootstrap-tagsinput {
		width: 100%;
	}

	.keyinput input {
		width: 150px;
	}

	.tagView input {
		display: none;
	}

	.tagView .bootstrap-tagsinput {
		padding: 0;
	}

	.opshow {
		opacity: 1;
	}

	.ophide {
		opacity: 0.5;
	}

	.aimg>img {
		width: 100px;
		height: 100px;
	}
</style>
</head>
<body class="white-bg" th:object="${article}">
	<h1 style="display: inline-block;padding-left: 10px;">文章修改</h1>
	<form class="form-horizontal m" id="form-article-edit">
		<input name="articleId" type="hidden" th:field="*{articleId}" id="articleId">
		<div class="row" style="padding: 10px">
			<div class="col-md-9">
				<!--   标题 -->
				<div class="form-group">
					<div class="col-sm-12">
						<input class="form-control" type="text" name="articleTitle" id="articleTitle"
							th:field="*{articleTitle}" placeholder="文章标题" />
					</div>
				</div>
				<!-- 固定链接|保存 -->
				<div class="form-group">
					<div class="row" style="padding-left: 15px; padding-right: 15px">
						<div class="col-sm-12">
							<div class="row">
								<div class="col-sm-6">
									<input class="form-control" type="text" name="articleUrl" id="articleUrl"
										th:field="*{articleUrl}" placeholder="固定链接" />
									<span class="help-block m-b-none"><i class="fa fa-info-circle"></i> 固定路径为：<span
											th:text="${@config.getKey('oly.cms.articleUrl.fixedPrefix')}"></span><span
											id="relativeUrl" th:text="*{articleUrl}"></span></span>
								</div>
								<div class="col-sm-6">
									<div class="btn-group" role="group"
										style="margin-top: 10px; float: right; margin-right: 40px;">
										<span class="btn btn-default" id="editOk">保存</span>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
				<!-- 关键词 -->
				<div class="form-group">
					<div class="col-sm-12 keyinput">
						<input class="form-control" type="text" name="keywords" id="articleKey" placeholder="关键词" />
					</div>
				</div>
				<!-- 内容 -->
				<div class="form-group">
					<div class="col-sm-12">
						<input type="hidden" name="articleContent" id="articleContent">
						<div id="editor" th:utext="*{articleContent}"></div>
					</div>
				</div>
			</div>

			<div class="col-md-3">
				<!-- 分类 -->
				<div class="form-group">
					<div class="ibox float-e-margins">
						<div class="ibox-title">
							<h5>选择分类</h5>
							<div class="ibox-tools">
								<a class="close-link"><i class="fa fa-question-circle" title="选择分类"></i></a><a
									class="add-link" onclick="addCat()"><i class="fa fa-plus-circle"
										title="添加分类"></i></a> <a class="collapse-link"><i class="fa fa-chevron-up"></i>
								</a>
							</div>
						</div>
						<div class="ibox-content" style="display: block;">
							<ul class="list-unstyled">
								<li class="tagView"><input class="form-control" type="text" name="cats" id="catInput" />
								</li>
								<li>
									<div class="input-group" style="padding-top: 10px">
										<input class="form-control" type="text" onclick="selectCatTree()" id="treeName"
											readonly th:value="${#arrays.isEmpty(cats)?'':cats[0].catName}"> <span
											class="input-group-addon"><i class="fa fa-search"></i></span>
									</div>
								</li>
							</ul>
						</div>
					</div>
				</div>
				<!-- 标签 -->
				<div class="form-group">
					<div class="ibox float-e-margins">
						<div class="ibox-title">
							<h5>选择标签</h5>
							<div class="ibox-tools">
								<a class="close-link"><i class="fa fa-question-circle" title="最多选择3个标签"></i></a> <a
									class="add-link" onclick="addTag()"><i class="fa fa-plus-circle"
										title="添加标签"></i></a> <a class="collapse-link"><i class="fa fa-chevron-up"></i>
								</a>
							</div>
						</div>
						<div class="ibox-content" style="display: block;">
							<ul class="list-unstyled">
								<li class="tagView"><input class="form-control" type="text" name="tags" id="tagInput" />
								</li>
								<li style="padding-top: 10px"><select class="selectpicker show-tick form-control"
										data-live-search="true" id="chooseTag" name="chooseTag" title="选择标签">
									</select></li>
							</ul>
						</div>
					</div>
				</div>
				<!-- 类型 -->
				<div class="form-group">
					<div class="ibox float-e-margins">
						<div class="ibox-title">
							<h5>文章类型</h5>
							<div class="ibox-tools">
								<a class="collapse-link"><i class="fa fa-chevron-up"></i> </a> <a class="close-link"><i
										class="fa fa-times"></i></a>
							</div>
						</div>
						<div class="ibox-content" style="display: block;">
							<div class="radio-box" th:each="dict : ${@dict.getType('cms_article_type')}">
								<input type="radio" th:id="${dict.dictCode}" name="articleType"
									th:value="${dict.dictValue}" th:field="*{articleType}">
								<label th:for="${dict.dictCode}" th:text="${dict.dictLabel}"></label>
							</div>
						</div>
					</div>
				</div>
				<!-- 评论 -->
				<div class="form-group">
					<div class="ibox float-e-margins">
						<div class="ibox-title">
							<h5>评论开关</h5>
							<div class="ibox-tools">
								<a class="collapse-link"><i class="fa fa-chevron-up"></i> </a> <a class="close-link"><i
										class="fa fa-times"></i></a>
							</div>
						</div>
						<div class="ibox-content" style="display: block;">
							<label class="radio-inline"> <input type="radio" checked name="allowComment" value="1"
									th:field="*{allowComment}">
								开启
							</label> <label class="radio-inline"> <input type="radio" name="allowComment" value="0"
									th:field="*{allowComment}">
								关闭
							</label>
						</div>
					</div>
				</div>
				<!-- seo描述 -->
				<div class="form-group">
					<div class="ibox float-e-margins">
						<div class="ibox-title">
							<h5>SEO描述</h5>
							<div class="ibox-tools">
								<a class="collapse-link"><i class="fa fa-chevron-up"></i> </a> <a class="close-link"><i
										class="fa fa-times"></i></a>
							</div>
						</div>
						<div class="ibox-content" style="display: block;">
							<textarea class="form-control" rows="3" name="description"
								th:field="*{description}"></textarea>
						</div>
					</div>
				</div>
				<!-- 评论 -->
				<div class="form-group">
					<div class="ibox float-e-margins">
						<div class="ibox-title">
							<h5>转载链接</h5>
							<div class="ibox-tools">
								<a class="close-link"><i class="fa fa-question-circle" title="文章来源，不填则为原创"></i></a> <a
									class="collapse-link"><i class="fa fa-chevron-up"></i> </a>
							</div>
						</div>
						<div class="ibox-content" style="display: block;">
							<input class="form-control" type="text" name="reprintUrl" th:value=${articleContent}
								id="reprintUrl" />
						</div>
					</div>
				</div>
				<!-- 缩略图 -->
				<input type="hidden" name="articleImg" id="articleImg" th:value=${articleImg}>
				<!-- 文章概况 -->
				<input type="hidden" id="summary" name="articleSummary" th:value=${articleSummary} />

			</div>
		</div>
	</form>

	<th:block th:include="include :: footer" />
	<th:block th:include="include::bootstrap-select-js" />
	<th:block th:include="include :: oly_froala_js" />
	<th:block th:include="include :: bootstrap-fileinput-js" />
	<th:block th:include="include :: oly_tagsinput_js" />
	<!-- 确认文章 -->
	<script type="text/html" id="okAddModel">
    <div class="form-group" style="padding-top:20px">
			<label class="col-sm-2 control-label">文章预览</label>
			<div class="col-sm-10">
				<textarea class="form-control" rows="3" id="articleSummary" placeholder="文章预览"></textarea>
			</div>
	</div>

    <div class="form-group" style="padding-top:80px">
			<label class="col-sm-2 control-label">选择封面</label>
			<div class="col-sm-10 aimg" >   
			</div>  
    </div>
    <div class="form-group text-center">
			<button type="button" class="btn btn-primary" id="saveArticle">保存文章</button>
	</div>
    </script>

	<script type="text/javascript" th:inline="JavaScript">
		var baseArticle = ctx + "cms/article";
		var baseTag = ctx + "cms/tag";
		var baseCat = ctx + "cms/cat";
		var articleSummary = [[*{ articleSummary }]];
		//初始化参数
		var tags = [[${ tags }]], cats = [[${ cats }]], keywords = [[*{ keywords }]],
			maxTag = [[${@config.getKey('oly.cms.articleTag.maxNum') }]],
		maxCat = [[${@config.getKey('oly.cms.articleCat.maxNum') }]],
		maxPhoto = [[${@config.getKey('oly.cms.articleImg.maxNum') }]],
		maxKeyword = [[${@config.getKey('oly.cms.articleKeyword.maxNum') }]];

		/* 初始化富文本编辑器 */
		var editor = new FroalaEditor("#editor", {
			// Set the language code.
			language: 'zh_cn',
			imageUploadURL: baseArticle + '/articleImgByFroala', //上传到本地服务器

		});
		$("#editOk").click(function () {
			if ($("input[name='cats']").val() === '') {
				layer.msg('请选择一个分类', { icon: 6 })
			}
			else if ($.validate.form("form-article-edit")) {
				//获取编辑内容
				const editorData = editor.html.get(true);
				layer.open({
					title: "确认信息",
					area: ['600px', '400px'],
					type: 1,
					content: $("#okAddModel").html(),
					success: function () {
						/*  getImgSrc($(".opshow")); */

						//填充图片
						var imgs = chooseImg(editorData);
						if (imgs.length > 0) {
							$.each(imgs, function (i, val) {
								$(".aimg").append("<img class='ophide' src='" + val + "' />")
							})
						}
						//填充描述
						$("#articleSummary").val(articleSummary);
						//初始化选择事件
						$(".aimg>img").click(function () {
							if ($(this).hasClass("opshow")) {
								$(this).removeClass("opshow");
								$(this).addClass("ophide");
								return;
							}
							if ($(this).hasClass("ophide") && $(".opshow").length < maxPhoto + 1) {
								$(this).removeClass("ophide");
								$(this).addClass("opshow");
								return;
							}
							else {
								layer.msg('最多选择' + maxPhoto + '张', { icon: 6 })
							}
						});
						//初始化提交
						$("#saveArticle").click(function () {
							$("#articleImg").val(getImgSrc($(".opshow")).toString());
							$("#summary").val($("#articleSummary").val());
							$("#articleContent").val(editorData);
							$.operate.saveTab(baseArticle + "/edit", $('#form-article-edit').serialize());
							layer.closeAll();
						});
					}
				});
			}
			else {
				layer.msg('表单验证未通过', { icon: 6 });
			}
		});

		function getImgSrc(dom) {
			var srcs = [];
			$.each(dom, function (i, val) {
				srcs.push($(this).attr("src"))
			});
			return srcs;
		}

		function chooseImg(str) {
			var data = []
			//获取img标签
			var imgReg = /<img.*?(?:>|\/>)/gi;
			//匹配src属性
			var srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i;
			var arr = str.match(imgReg);
			if (arr == null) { return data; }
			for (var i = 0; i < arr.length; i++) {
				var src = arr[i].match(srcReg);
				//获取图片地址
				if (src[1]) {
					data.push(src[1]);
				}
			}
			return data;
		}

		function chooseSummary(html) {
			html = html.replace(/<\/?[^>]*>/g, ''); //去除HTML tag
			html = html.replace(/[ | ]*\n/g, '\n'); //去除行尾空白
			html = html.replace(/ /ig, '');//去掉
			return html;
		}



		//保存文章
		$("#form-article-edit").validate({
			errorPlacement: function (error, element) {
				layer.tips(error.html(), element, { tipsMore: true });
			},
			rules: {
				articleType: {
					required: true
				},
				allowComment: {
					required: true
				},
				reprintUrl: {
					url: true
				},
				articleTitle: {
					required: true,
					remote: {
						url: baseArticle + "/checkArticleTitle",
						type: "post",
						dataType: "json",
						data: {
							"articleId": $("#articleId").val()
							,
							"articleTitle": function () {
								if ($("#catInput").val().length != null) {
									return $.common.trim($("#articleTitle").val());
								} else {
									layer.msg('类别未选', {
										icon: 1,
										time: 1000 //2秒关闭（如果不配置，默认是3秒）
									}, function () {
										layer.closeAll();
									});
									return;
								}
							}
						},
						dataFilter: function (data, type) {
							return $.validate.unique(data);
						}
					}
				}, articleUrl: {
					required: true,
					remote: {
						url: baseArticle + "/checkArticleUrl",
						type: "post",
						dataType: "json",
						data: {
							"articleUrl": function () {
								return $.common.trim($("#articleUrl").val());
							},
							"articleId": $("#articleId").val()
						},
						dataFilter: function (data, type) {
							if (data == "0") {
								$("#relativeUrl").text($("#articleUrl").val());
							}
							return $.validate.unique(data);
						}
					}
				}
			}
			,
			messages: {
				"articleTitle": {
					remote: "文章标题已经存在"
				},
				"articleUrl": {
					remote: "文章路径已经存在"
				}
			},
			focusCleanup: true
		});


		/*文章管理-新增-选择类目树*/
		function selectCatTree() {
			var treeId = $("#treeId").val();
			var catId = treeId > 0 ? treeId : 1;
			var url = baseCat + "/selectCatTree/1/" + catId;
			var options = {
				title: '类目选择',
				width: "380",
				url: url,
				callBack: doSubmit
			};
			$.modal.openOptions(options);
		}
		//选择类目回调
		function doSubmit(index, layero) {
			var body = layer.getChildFrame('body', index);
			var catId = body.find('#treeId').val();
			var catName = body.find('#treeName').val();
			$("#treeName").val(catName);
			//$('#catInput').tagsinput('removeAll');//不会调用移除事件
			if ($("#catInput").tagsinput('items').length > cats) {
				layer.msg('只允许添加' + $("#catInput").tagsinput('items').length + '个分类', {
					icon: 1,
					time: 2000 //2秒关闭（如果不配置，默认是3秒）
				});
			}
			//会调用beforeItemAdd
			$("#catInput").tagsinput('add', { 'catId': catId, 'catName': catName });
			layer.close(index);
		};
		//初始化文章标签
		$("#tagInput").tagsinput({
			maxTags: maxTag,
			itemValue: 'tagId',
			itemText: 'tagName'
		});
		//初始化文章标签
		$("#catInput").tagsinput({
			maxTags: maxCat,
			itemValue: 'catId',
			itemText: 'catName'
		});
		function tagsSync(url, data, ent) {
			return new Promise(function (resolve) {
				$.post(url, data,
					function (data, status) {
						if (data.code === 0) {
							layer.msg('操作成功', {
								icon: 1,
								time: 2000 //2秒关闭（如果不配置，默认是3秒）
							});
						}
						else {
							layer.msg('操作失败', {
								icon: 1,
								time: 2000 //2秒关闭（如果不配置，默认是3秒）
							});
						}
						resolve(data.code);
					});
			});
		}
		function tagsEvent() {
			$('#catInput').on('beforeItemAdd', function (event) {
				var data = {
					'articleId': $("#articleId").val(),
					'catId': event.item.catId
				}, url = baseArticle + '/addCatArticle';
				tagsSync(url, data, event).then(function (res) {
					if (res === 0) {
						event.cancel;
					}
					else {
						$('#catInput').tagsinput('remove', event.item);
					}
				});
			});

			$('#catInput').on('beforeItemRemove', function (event) {
				var data = {
					'articleId': $("#articleId").val(),
					'catId': event.item.catId
				}, url = baseArticle + '/removeCatArticle';
				tagsSync(url, data, event).then(function (res) {
					if (res === 0 || res === 500) {
						event.cancel
					}
					else {
						$('#catInput').tagsinput('remove', event.item);
					}
				});
			});
			/* 添加成功后调用*/
			$('#tagInput').on('beforeItemAdd', function (event) {
				var data = {
					'articleId': $("#articleId").val(),
					'tagId': event.item.tagId
				}, url = baseArticle + '/addTagArticle';
				tagsSync(url, data, event).then(function (res) {

					if (res === 0 || res === 500) {
						event.cancel
					}
					else {
						$('#tagInput').tagsinput('remove', event.item);
					}
					getTag();
				});
			});

			//删除成功后调用
			$('#tagInput').on('beforeItemRemove', function (event) {

				var data = {
					'articleId': $("#articleId").val(),
					'tagId': event.item.tagId
				}, url = baseArticle + '/removeTagArticle';
				tagsSync(url, data, event).then(function (res) {
					if (res === 0) {
						event.cancel
					}
					else {

						$('#tagInput').tagsinput('remove', event.item);
					}
					getTag();
				});
			});
		};
		function initView() {
			//初始化标签页
			if (tags != null) {
				$.each(tags, function (i, e) {//i是索引，e是json对象
					$("#tagInput").tagsinput('add', { 'tagId': e.tagId, 'tagName': e.tagName });
				});
			}
			//初始化类目页
			if (cats != null) {
				$.each(cats, function (i, e) {//i是索引，e是json对象
					$("#catInput").tagsinput('add', { 'catId': e.catId, 'catName': e.catName });
				});
			}
			//初始化标签事件
			tagsEvent();

		}
		initView();

		//初始化关键词
		$("#articleKey").tagsinput({
			maxTags: maxKeyword
		});
		//添加关键词
		$('#articleKey').tagsinput(
			"add", keywords
		);
		//选择标签
		$("#chooseTag").change(function () {
			var k = $(this).val();
			var n = $(this).find("option:selected").text().split("(")[0];
			if (n != "") {
				if ($("#tagInput").tagsinput('items').length > maxTag) {
					layer.msg('最多允许添加' + $("#tagInput").tagsinput('items').length + '个标签', {
						icon: 1,
						time: 2000 //2秒关闭（如果不配置，默认是3秒）
					});
				}
				$("#tagInput").tagsinput('add', { 'tagId': k, 'tagName': n });
			}

		});
		//获取标签列表
		function getTag() {
			$.get(baseTag + "/listTagNotHide", function (data, status) {
				$("#chooseTag").empty();
				$.each(data, function (i, e) {//i是索引，e是json对象
					$("#chooseTag").append("<option value=" + e.tagId + ">" + e.tagName + "(" + ((e.tagCount) === null ? 0 : e.tagCount) + ")</option>");
				});
				$("#chooseTag").selectpicker("refresh");
			});
		}
		//初始化下拉
		$(window).on('load', function () {
			$('#chooseTag').selectpicker();
			getTag();
		});
    
		function addCat() {
			$.modal.open('添加分类', baseCat + "/add/0");
		}

		function addTag() {
			$.modal.open('添加标签', baseTag + "/add");
		}
	</script>
</body>

</html>